package appController

import (
	"CMETO/models"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

// app部分的接口
type CourseController struct{}

// @Summary 分类查询
// @Description 查询分类
// @Tags 课程分类管理
// @Accept json
// @Produce json
// @Param page query string false "页码"
// @Param pageSize query string false "尺寸"
// @Param name query string false "分类名"
// @Success 200 {object} models.ResultCommon[[]models.CourseType] "查询成功"
// @Success 400 {object} models.ErrorResult "查询失败"
// @Router /app/courseType [get]
// @Security JWT
func (courseType CourseController) QueryCourseTypes(ctx *gin.Context) {
	page, _ := strconv.Atoi(ctx.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(ctx.DefaultQuery("pageSize", "10"))
	nameStr := ctx.DefaultQuery("name", "")
	name := "%" + nameStr + "%"
	typeList := []models.CourseType{}
	models.DB.Model(&models.CourseType{}).Where("is_delete!=1 AND name like ?", name).Limit(pageSize).Offset(pageSize * (page - 1)).Find(&typeList)
	var total int64
	models.DB.Table("course_types").Where("is_delete!=1 AND name like ?", name).Count(&total)
	result := &models.ResultByPage[models.CourseType]{
		Msg:      "ok",
		Code:     "200",
		Total:    total,
		Page:     page,
		PageSize: pageSize,
		Result:   typeList,
	}
	ctx.JSON(http.StatusOK, result)
}

// @Summary 课程查询
// @Description 查询课程(分类)
// @Tags APP管理
// @Accept json
// @Produce json
// @Param page query string false "页码"
// @Param pageSize query string false "尺寸"
// @Param id query string false "分类"
// @Success 200 {object} models.ResultCommon[[]models.Course] "查询成功"
// @Success 400 {object} models.ErrorResult "查询失败"
// @Router /app/course/bysort [get]
// @Security JWT
func (course CourseController) QueryCourses(ctx *gin.Context) {
	page, _ := strconv.Atoi(ctx.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(ctx.DefaultQuery("pageSize", "10"))
	id := ctx.DefaultQuery("id", "0")
	courseList := []models.CourseFormat{}
	models.DB.Table("courses").
		Where("is_delete!=1 AND tid = ?", id).
		Limit(pageSize).Offset(pageSize * (page - 1)).
		Scan(&courseList)
	var total int64
	models.DB.Table("courses").Where("is_delete!=1 AND tid = ?", id).Count(&total)
	result := &models.ResultByPage[models.CourseFormat]{
		Msg:      "ok",
		Code:     "200",
		Total:    total,
		Page:     page,
		PageSize: pageSize,
		Result:   courseList,
	}
	ctx.JSON(http.StatusOK, result)
}
